package com.liarjo.mywebsiteapi.controller.login;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.liarjo.mywebsiteapi.pojo.User;
import com.liarjo.mywebsiteapi.util.JwtUtil;

@Service
public class LoginService {
    @Autowired
    private LoginMapper loginMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtil jwtUtil;

    public LoginResult login(LoginRequest loginRequest) {
        User user = loginMapper.findByUserName(loginRequest.getUserName());
        if (user == null) {
            throw new RuntimeException("用户名不存在");
        }
        if (!passwordEncoder.matches(loginRequest.getPassword(), user.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }

        Map<String, Object> customClaims = new HashMap<>();
        customClaims.put("role", user.getRole());
        String token = jwtUtil.generateToken(user.getId().toString(), customClaims);

        LoginResult loginResult = new LoginResult(token);
        BeanUtils.copyProperties(user, loginResult);
        return loginResult;
    }
}
